package com.woniuxy.servicelayer.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.dal.entity.*;
import com.woniuxy.dal.mapper.*;
import com.woniuxy.servicelayer.RangeService;
import com.woniuxy.servicelayer.util.Base64Util;
import com.woniuxy.servicelayer.util.JwtUtil;
import com.woniuxy.servicelayer.util.Md5Util;
import com.woniuxy.servicelayer.vo.CommentVo;
import com.woniuxy.servicelayer.vo.DetailVo;
import org.apache.ibatis.io.ResolverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.io.Serializable;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author rjq51
 * @description 针对表【range(靶场表)】的数据库操作Service实现
 * @createDate 2023-03-27 17:02:43
 */
@Service
public class RangeServiceImpl extends ServiceImpl<RangeMapper, Ranges>
        implements RangeService {

    @Autowired
    RangeMapper rangeMapper;

    @Autowired
    TestMapper testMapper;

    @Autowired
    CollectMapper collectMapper;

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    UserinfoMapper userinfoMapper;

    @Autowired
    HistoryMapper historyMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 增加靶场
     */
    @Override
    public int addRange(Ranges range) {
        return rangeMapper.insert(range);
    }

    /**
     * 删除靶场
     */
    @Override
    public int delRange(Integer rangeId) {
        return rangeMapper.deleteById(rangeId);
    }

    /**
     * 修改靶场
     */
    @Override
    public int updateRange(Ranges range) {
        return rangeMapper.updateById(range);
    }

    /**
     * 查询靶场信息
     */
    @Override
    public Page<Ranges> selectRange(Integer currentPage, Integer pageSize, String keyword,Integer order,Integer type) {
        Page<Ranges> page = new Page<>(currentPage,pageSize);
        QueryWrapper<Ranges> rangeQueryWrapper = new QueryWrapper<>();
        if(type != 1){
            rangeQueryWrapper.eq("rangeType",type);
        }
        if(StringUtils.isNotBlank(keyword)){
            rangeQueryWrapper.like("rangeName",keyword);
        }
        if (order == 1)
            rangeQueryWrapper.orderByAsc("visitorsCount");

        return rangeMapper.selectPage(page,rangeQueryWrapper);
    }

    /**
     * 查询靶场信息
     * 副本
     */
    public Page<Ranges> selectRangeCope(Integer currentPage, Integer pageSize, String keyword) {
        Page<Ranges> page = new Page<>(currentPage,pageSize);
        QueryWrapper<Ranges> rangeQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(keyword)){
            rangeQueryWrapper.like("rangeName",keyword);
        }

        return rangeMapper.selectPage(page,rangeQueryWrapper);
    }

    /**
     * 分类查询靶场
     */
    @Override
    public List<Ranges> classificationQuery(Integer typeId) {
        QueryWrapper<Ranges> rangeQueryWrapper = new QueryWrapper<>();
        rangeQueryWrapper.eq("rangeType",typeId);
        return rangeMapper.selectList(rangeQueryWrapper);
    }

    @Override
    public Ranges getRange(Object id) {
        QueryWrapper<Ranges> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rangeId",id);
        return rangeMapper.selectList(queryWrapper).get(0);
    }

    @Override
    public Integer addVisitCount(Object rangeId) {
        QueryWrapper<Ranges> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rangeId", rangeId);
        Ranges ranges = rangeMapper.selectList(queryWrapper).get(0);
        ranges.setVisitorsCount(ranges.getVisitorsCount() + 1);
        int updateById = rangeMapper.updateById(ranges);
        if (updateById == 1){
            return 200;
        }
        return null;
    }

    @Override
    public DetailVo queryDetailStats(Object rangeId, String token) {
        Object userId = JwtUtil.parseValue(token, "userId");
        QueryWrapper<Ranges> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rangeId",rangeId);
        Ranges ranges = rangeMapper.selectList(queryWrapper).get(0);
        DetailVo detailVo = new DetailVo();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime oneWeekAgo = now.minusWeeks(1);
        QueryWrapper<Test> wrapper = new QueryWrapper<>();
        wrapper.lambda().ge(Test::getCreateTime, oneWeekAgo);
        List<Test> tests = testMapper.selectList(wrapper);
        detailVo.setWeeklyViews(tests.size());
        detailVo.setTotalViews(ranges.getVisitorsCount());
        QueryWrapper<Collect> collectQueryWrapper = new QueryWrapper<>();
        collectQueryWrapper.eq("rangeId",rangeId);
        List<Collect> collects = collectMapper.selectList(collectQueryWrapper);
        detailVo.setFavoritesCount(collects.size());
        for (Collect collect : collects) {
            if (collect.getUserId() == userId){
                detailVo.setIsFavorited(1);
            }
        }
        return detailVo;
    }

    @Override
    public List<CommentVo> fetchComments(Object rangeId) {
        List<CommentVo> commentVos = new ArrayList<>();
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.eq("rangeId",rangeId);
        List<Comment> comments = commentMapper.selectList(commentQueryWrapper);
        if (!comments.isEmpty()){
            for (Comment comment : comments) {
                CommentVo commentVo = new CommentVo();
                commentVo.setComment(comment);
                QueryWrapper<Userinfo> userinfoQueryWrapper = new QueryWrapper<>();
                userinfoQueryWrapper.eq("userId",comment.getUserId());
                Userinfo userinfo = userinfoMapper.selectList(userinfoQueryWrapper).get(0);
                commentVo.setUserIcon(userinfo.getUserIcon());
                commentVo.setUserName(userinfo.getUsername());
                commentVos.add(commentVo);
            }
        }
        return commentVos;
    }

    @Override
    public void sendComment(Object rangeId, Object token, Object comment) {

        Comment comment1 = new Comment();
        comment1.setCommentDetail(comment.toString());
        comment1.setRangeId((Integer) rangeId);
        comment1.setUserId((Integer) JwtUtil.parseValue(token.toString(), "userId"));
        commentMapper.insert(comment1);

    }

//    @Override
//    public void addTest(Object rangeId, Object token,Object status) {
//        History history = new History();
//        history.setStatus((Integer) status);
//        if ((Integer) status == 1){
//            QueryWrapper<Userinfo> userinfoQueryWrapper = new QueryWrapper<>();
//            userinfoQueryWrapper.eq("userId",JwtUtil.parseValue(token.toString(), "userId"));
//            Userinfo userinfo = userinfoMapper.selectList(userinfoQueryWrapper).get(0);
//            userinfo.setRangeScore(userinfo.getRangeScore() + 100);
//            userinfoMapper.updateById(userinfo);
//        }
//        history.setRangeId((Integer) rangeId);
//        Date currentDate = new Date();
//        Timestamp timestamp = new Timestamp(currentDate.getTime());
//        history.setCreateTime(timestamp);
//        history.setRangeName(rangeMapper.selectById((Serializable) rangeId).getRangeName());
//        history.setUserId((Integer) JwtUtil.parseValue(token.toString(), "userId"));
//        historyMapper.insert(history);
//    }

    @Override
    public String generateFlag(Object rangeId,String token) {
        String s = generateRandomString(16);
        String flag = Base64Util.base64Encode(s);
//        String flag = JwtUtil.createTokenSingleInfo(60, "flag", s);
//        stringRedisTemplate.opsForValue().set(token,flag);
        stringRedisTemplate.opsForValue().set(token,flag,60, TimeUnit.SECONDS);
        System.out.println(s);
        System.out.println(s);
        System.out.println(s);
        System.out.println(s);
        return flag;
    }

    @Override
    public Integer queryFlag(Object flag,String token) {
        String originFlag = flag.toString();
        String targetFlag = stringRedisTemplate.opsForValue().get(token);
        assert targetFlag != null;
        String currentFlag = Base64Util.base64Decode(targetFlag);
        if (originFlag.equals(currentFlag)){;
            stringRedisTemplate.delete(token);
            return 200;
        }
        return null;
    }

    //测试用，生成字符串
    public static String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(characters.length());
            sb.append(characters.charAt(randomIndex));
        }

        return sb.toString();
    }


    //====
    @Override
    public Ranges getRangeById(Integer rangeId) {
        QueryWrapper<Ranges> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rangeId",rangeId);
        return rangeMapper.selectById(rangeId);
    }

}




